<template>
  <a-space direction="vertical">
    <a-card title="搜索">
      <a-form
        ref="searchRef"
        name="searchBar"
        :model="searchFormState"
        :labelCol="{ span: 5, offset: 1 }"
        @finish="handleSearch"
      >
        <a-row :gutter="24">
          <a-col :span="8">
            <a-form-item name="webServId" label="用户名">
              <a-input
                v-model:value="searchFormState.useName"
                placeholder=""
              ></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item name="servRemark" label="用户Id">
              <a-input
                v-model:value="searchFormState.useId"
                placeholder=""
              ></a-input>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="24" style="text-align: right">
            <a-button type="primary" html-type="submit" :loading="searchLoading"
              >搜索</a-button
            >
            <a-button
              style="margin: 0 8px"
              @click="() => searchRef?.resetFields()"
              >重置</a-button
            >
          </a-col>
        </a-row>
      </a-form>
    </a-card>
    <a-card>
      <a-space>
        <a-button @click="showModal" type="primary"
          ><template #icon> <appstore-add-outlined /> </template>新增</a-button
        >
        <a-button @click="showEditModal"
          ><template #icon> <form-outlined /> </template>修改</a-button
        >
        <a-button @click="showDelete"
          ><template #icon> <form-outlined /> </template>删除</a-button
        >
      </a-space>
    </a-card>
    <a-card title="查询结果">
      <a-table
        class="ant-table-striped"
        :rowClassName="
          (_record, index) => (index % 2 === 1 ? 'table-striped' : null)
        "
        :columns="columns"
        :data-source="data"
        rowKey="webServId"
        :loading="searchLoading"
        :rowSelection="rowSelection"
        @change="
          (pagination: any) => {
            handleSearch(pagination);
          }
        "
        :pagination="{
          position: [`bottomRight`],
          showSizeChanger: true,
          showQuickJumper: true,
          current: pageIndex,
          pageSize,
          total: total,
          showTotal: (total) => `总计 ${total} 条记录`,
        }"
      >
        <template #bodyCell="{ column, text }">
          <template v-if="column.dataIndex === 'name'">
            <a>{{ text }}</a>
          </template>
        </template>
      </a-table>
    </a-card>
    <a-modal
      ref="modalRef"
      v-model:visible="visible"
      @ok="handleOk"
      style="width: 1200px; top: 0"
    >
      <template #title>
        <div ref="modalTitleRef" style="width: 100%; cursor: move">
          {{ currentAction }}服务器注册
        </div>
      </template>
      <template #modalRender="{ originVNode }">
        <div :style="transformStyle">
          <component :is="originVNode" />
        </div>
      </template>

      <a-form
        ref="formRef"
        :model="formState"
        :labelCol="{ span: 5, offset: 1 }"
        name="form_in_modal"
      >
        <a-row :gutter="24">
          <a-col :span="14" :offset="6">
            <a-form-item
              name="useName"
              label="用户名"
              :rules="[{ required: true, message: '请输入用户名' }]"
            >
              <a-input
                v-model:value="formState.useName"
               />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :span="14" :offset="6">
            <a-form-item name="useId" label="用户选项">
              <a-select
                :allowClear="true"
                v-model:value="formState.useId"
                placeholder=""
              >
                <a-select-option value="ismm">是</a-select-option>
                <a-select-option value="local">否</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-modal>
  </a-space>
</template>
<script lang="ts" setup>
// base library
import { LISTHEADER } from "./config";
import { serverQuery, serverAdd, serverEdit } from "@/api/supperManagement";
import { onMounted } from "@vue/runtime-core";
import {
  computed,
  reactive,
  ref,
  toRaw,
  unref
} from "vue";
import { FormInstance, message, Modal } from "ant-design-vue";
import { useDraggable } from "@vueuse/core";
import { ExclamationCircleOutlined } from "@ant-design/icons-vue";

const searchRef = ref<FormInstance>();
let searchLoading = ref(true);
const searchFormState: { [propName: string]: any } = reactive({});

const columns = LISTHEADER;
let pageIndex = ref(1);
let pageSize = ref(10);
let total = ref(0);
let data = ref([]);
const handleSearch = (values?: any) => {
  searchLoading.value = true;
  console.log("Received values of form: ", values);
  console.log("searchFormState: ", searchFormState);
  let parameter = { ...searchFormState };
  if (values?.current) {
    // 分页切换
    pageIndex.value = values?.current;
    pageSize.value = values?.pageSize;
  } else {
    // 搜索
    selectedRowKeys.value = [];
    selectedRows.value = [];
    pageIndex.value = 1;
  }
  const requestParameters = Object.assign({}, parameter, {
    pageIndex: pageIndex.value,
    pageSize: pageSize.value,
  });
  console.log("loadData request parameters:", requestParameters);

  serverQuery(requestParameters).then(
    (res: {
      code: number | string;
      msg: string;
      total: number;
      datas: any;
    }) => {
      searchLoading.value = false;
      const { code, msg, total: count, datas } = res;
      if (code === "777") {
        data.value = datas;
        total.value = count;
      } else {
        total.value = 0;
        data.value = [];
        pageIndex.value = 1;
        message.error(msg);
      }
    }
  );
};

const selectedRowKeys = ref<string[]>([]); // Check here to configure the default column
const selectedRows = ref<T[]>([]);
const onSelectChange = (changableRowKeys: string[], changableRows: T[]) => {
  console.log("selectedRowKeys changed: ", changableRowKeys);
  selectedRowKeys.value = changableRowKeys.length > 1 ? [changableRowKeys.pop()] : changableRowKeys;
  selectedRows.value =
    changableRows.length > 1 ? [changableRows.pop()] : changableRows;
};
const rowSelection = computed(() => {
  return {
    selectedRowKeys: unref(selectedRowKeys),
    onChange: onSelectChange,
    hideDefaultSelections: true,
  };
});
enum action {
  add = "新增",
  edit = "编辑",
}
const currentAction = ref(action.add);
const visible = ref<boolean>(false);
const modalTitleRef = ref<HTMLElement>(null);

const { x, y, isDragging } = useDraggable(modalTitleRef);
const startX = ref<number>(0);
const startY = ref<number>(0);
const startedDrag = ref(false);
const transformX = ref(0);
const transformY = ref(0);
const preTransformX = ref(0);
const preTransformY = ref(0);
const dragRect = ref({ left: 0, right: 0, top: 0, bottom: 0 });


interface FormValues {
  useName: string;
  useId: string;
}
const formRef = ref<FormInstance>();
const formState = reactive<FormValues>({
  useName: "",
  useId: ""
});
const showModal = () => {
  visible.value = true;
  formRef.value?.resetFields();
  currentAction.value = action.add;
  formState.useName = "";
  formState.useId = "";

};
const showEditModal = () => {
  if (selectedRowKeys.value.length > 1)
    message.error("仅能选择一条记录进行操作");
  if (selectedRowKeys.value.length === 0)
    message.error("请选择一条记录进行操作");
  if (selectedRowKeys.value.length === 1) {
    currentAction.value = action.edit;
    visible.value = true;
    formRef.value?.resetFields();
    formState.useName = selectedRows.value[0].webServId;
    formState.useId = selectedRows.value[0].webServIp;
  }
};
const handleOk = (e: MouseEvent) => {
  console.log(e);
  // visible.value = false;

  formRef.value
    .validateFields()
    .then((values) => {
      console.log("Received values of form: ", values);
      console.log("formState: ", toRaw(formState));
      visible.value = false;

      if (currentAction.value === action.add) {
        serverAdd(formState).then((res) => {
          const { code, msg } = res;
          if (code === "777") {
            Modal.success({
              title: msg,
            });
            formRef.value?.resetFields();
            console.log("reset formState: ", toRaw(formState));
          } else {
            Modal.error({
              title: msg,
            });
          }
          handleSearch();
        });
      }
      if (currentAction.value === action.edit) {
        serverEdit(formState).then((res) => {
          const { code, msg } = res;
          if (code === "777") {
            Modal.success({
              title: msg,
            });
            formRef.value?.resetFields();
            console.log("reset formState: ", toRaw(formState));
          } else {
            Modal.error({
              title: msg,
            });
          }
          handleSearch();
        });
      }
    })
    .catch((info) => {
      console.log("Validate Failed:", info);
    });
};
onMounted(() => {
  searchLoading.value = false;
  //   handleSearch();
});
</script>
<script lang="ts">
import {
  AppstoreAddOutlined,
  FormOutlined,
  DeleteOutlined,
  UsergroupAddOutlined,
  UserOutlined,
  ShareAltOutlined,
} from "@ant-design/icons-vue";

export default {
  name: "userConfig",
  components: {
    AppstoreAddOutlined,
    FormOutlined,
    DeleteOutlined,
    UsergroupAddOutlined,
    UserOutlined,
    ShareAltOutlined,
  },
};
</script>

<style type="less" scoped>
/* .ant-form-item-label > label {
  width:150px!important;
  justify-content: end!important;
} */
.ant-table-striped :deep(.table-striped) td {
  background-color: #fafafa;
}

.ant-table-striped
  /deep/
  .ant-table-thead
  .ant-table-selection-column
  .ant-checkbox-wrapper {
  display: none;
}
</style>
